package com.example.hasee.xiqing.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Toast;


import com.example.hasee.xiqing.MyApplication;
import com.example.hasee.xiqing.R;
import com.example.hasee.xiqing.WebActivity;
import com.example.hasee.xiqing.pojo.News;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * Created by wanxiang on 2017/4/12.
 */
//动态Fragment
    @ContentView(R.layout.fragment_news)
public class NewsFragment extends Fragment implements RadioGroup.OnCheckedChangeListener, AdapterView.OnItemClickListener {
    @ViewInject(R.id.news_xwkx)
    RadioButton xwkx;
    @ViewInject(R.id.news_list)
    ListView lv;
    @ViewInject(R.id.news_guide)
    RadioGroup newsguide;

    private List<News> newslist;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        Log.i("news fragment: ", "...On Create...");
        newsguide.setOnCheckedChangeListener(this);//新闻分类导航的监听事件
        lv.setOnItemClickListener(this);
        init();
        return view;
    }


    //初始显示新闻动态
    public void init(){
        Context context = MyApplication.getInstance();//获取上下文
        xwkx.setChecked(true);
        String newstype = "xwkx/";
        getConnection(newstype, context);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Map<String,Object> item = (Map<String,Object>)lv.getItemAtPosition(position);
        String url = (String) item.get("link");
        Intent intent = new Intent();
        intent.setClass(view.getContext(), WebActivity.class);
        intent.putExtra("url",url);
        startActivity(intent);
    }
    //新闻类型切换监听事件
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        Context context = MyApplication.getInstance();
        String newstype = null;
        switch (checkedId){
            case R.id.news_xwkx://新闻快讯
                newstype="xwkx";
                break;
            case R.id.news_rcpy://人才培养
                newstype="rcpy";
                break;
            case R.id.news_tzgg://通知公告
                newstype="tzgg";
                break;
            case R.id.news_kjdt://科技动态
                newstype="kjdt";
                break;
        }
        getConnection(newstype, context);
    }

    //将新闻类型转换以显示在列表中
    public Map<String, Object> newsToItem(News n){
        Map<String, Object> map=new HashMap<>();
        map.put("title",n.getTitle());
        map.put("date",n.getDate());
        map.put("link",n.getLink());
        return map;
    }

    //解析网页数据得到新闻项
    public List<News> getData(String result) {
        List<News> lnb= new ArrayList<>();
        String temp = result.substring(result.indexOf("<ul class=\"nlist")+20,result.indexOf("<div class=\"pages")-30);
        String[] str = temp.split("<li><em>");
        for (int i = 1; i < str.length; i++) {
            News nb= new News();
            nb.setDate(str[i].split("</em")[0]);
            nb.setLink("http://www.xjqd.sd.cn"+str[i].split("href=\"")[1].split("\">")[0]);
            nb.setTitle(str[i].split("\">")[1].split("</a")[0]);
            lnb.add(nb);
        }
        return lnb;
    }

    //建立连接
    public void getConnection(String newstype, final Context context){
        RequestParams params=new RequestParams("http://www.xjqd.sd.cn/news/"+newstype);//请求参数
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                List<Map<String,Object>> init=new ArrayList<>();
                newslist=getData(result);
                for (News n:newslist){
                    Map<String, Object> map=newsToItem(n);
                    init.add(map);
                }
                SimpleAdapter InitAdapter=new SimpleAdapter(context, init, R.layout.newslist_item,
                        new String[]{"title", "date"},
                        new int[]{R.id.newsitem_title, R.id.newsitem_date});
                lv.setAdapter(InitAdapter);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), "连接失败，请重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
